########################################################
### 这里的函数是修改word文档的作用，注意，它们是不安全的！！！###
########################################################

from copy import deepcopy

from .utils import *

# 用来删除给定的段落（字段，图表等）
def delete_element(p: Element) -> None:
    p_element = p._element
    # 这一步是删除了word文档中的xml文件中的相应的部分，
    # 但是对python中的各种对象毫无影响。
    p_element.getparent().remove(p_element)


def move_elements(
    elements_to_move: Element | list[Element], element_of_direction: Element, **kwargs
):
    e = element_of_direction._element
    if type(elements_to_move) == list:
        pass
    else:
        move = [elements_to_move]

    parent = e.getparent()
    index = parent.index(e)

    if kwargs.get("next", True) & (not kwargs.get("previous", False)):
        for i in range(len(move)):
            if kwargs.get("copy", False):
                copy_element = deepcopy(move[i])._element
            else:
                copy_element = move[i]._element
            parent.insert(index + i + 1, copy_element)
    else:
        for i in range(len(move)):
            if kwargs.get("copy", False):
                copy_element = deepcopy(move[i])._element
            else:
                copy_element = move[i]._element
            parent.insert(index + i, copy_element)


def move_table(table: Table, element: Element, **kwargs):
    if isinstance(table, Table):
        move_elements(table, element, **kwargs)
    else:
        TypeError("The first variable should be a type of docx table.")


def _change_match(run: Run, new_str: str, reg_str: Reg) -> None:
    """ """

    run.text = re.sub(reg_str, new_str, run.text)


def change_question_number(
    p: Paragraph, new_int: int, reg_str: Reg = RE_QUESTION_NUMBER_STR
) -> None:
    _change_match(p.runs[0], str(new_int), reg_str)


def insert_run(p: Paragraph | Paragraphs,index:int, new_str: str, **kwargs) -> None:
    p.add_run(new_str)
    move_elements(p.runs[-1], p.runs[index], **kwargs)


# 更换题源
def format_resource(p: Paragraph) -> None:
    answer = get_resource(p)
    if answer:
        source_text = str(SourceType(answer))
        in_brackets = False
        if source_text:
            for run in p.runs:
                check_in = re.match(r"([\W\w]*?（)", run.text)
                check_out = re.match(r"[\W\w]*?(）[\W\w]*)", run.text)
                if check_in and check_out:
                    run.text = run.text.replace(answer, source_text)
                    # print(run.text.replace(answer,source_text))
                    break
                if check_in and (not check_out):
                    in_brackets = True
                    run.text = check_in.group(1)
                    # print(check_in.group(1))
                    continue
                if in_brackets and (not check_out):
                    run.text = ""
                    # print(run.text)
                if check_out:
                    run.text = source_text + check_out.group(1)
                    # print(source_text+check_out.group(1))
                    break
        else:
            for run in p.runs:
                check_in = re.match(r"([\W\w]*?)（", run.text)
                check_out = re.match(r"[\W\w]*?）([\W\w]*)", run.text)
                if check_in and check_out:
                    run.text = run.text.replace("（" + answer + "）", "")
                    break
                if check_in and (not check_out):
                    in_brackets = True
                    run.text = check_in.group(1)
                    continue
                if in_brackets and (not check_out):
                    run.text = ""
                if check_out:
                    run.text = check_out.group(1)
                    break


###############################################
##### 之前写的函数，现在觉得没什么意思，不过可以保留。
###############################################


# 调换星星“★”
def swap_stars(p: Paragraph) -> Union[str, None]:
    check = re.match(r"(\d+[\.．])[\w\W]*?(★+)([\w\W]+)", p.text)
    if check:
        return check.group(1) + check.group(3) + check.group(2)
